package com.bruceewu.galleryphoto.utis;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import android.text.TextUtils;

import com.bruceewu.galleryphoto.bean.ImageBean;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImageChooser {

    public static void showChoose(Context context, int requestCode) {
        checkPermission(context, () -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            try {
                ((Activity) context).startActivityForResult(Intent.createChooser(intent, "Select a File Path"), requestCode);
            } catch (Exception ex) {
                ToastUtils.show(ex.getMessage());
            }
        });
    }

    @SuppressLint("CheckResult")
    public static void checkPermission(Context context, Runnable next) {
        new RxPermissions((Activity) context)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        next.run();
                    } else {
                        ToastUtils.show("请授予读取文件的权限,否则无法读取图片.");
                    }
                });
    }

    //查找图片，排序，排除之前的图片，直接从中间开始
    public static List<ImageBean> filterImgs(String dir, String img) {

        //过滤合格的图片
        List<ImageBean> imgs = FileUtils.files(dir);

        //排序
        Collections.sort(imgs, (first, second) -> first.name().compareTo(second.name()));

        //已目前图片为准,后面的放前面,前面的放后面,保证图片不被截取
        if (!TextUtils.isEmpty(img)) {
            File lastFile = new File(img);
            if (!imgs.isEmpty() && lastFile.exists() && lastFile.isFile()) {
                String lastPath = lastFile.getAbsolutePath();
                int size = imgs.size();
                for (int i = 0; i < imgs.size(); i++) {
                    ImageBean item = imgs.get(i);
                    if (TextUtils.equals(item.path(), lastPath)) {
                        List<ImageBean> result = new ArrayList<>();
                        List<ImageBean> afterList = imgs.subList(i, size);
                        result.addAll(afterList);
                        List<ImageBean> preList = imgs.subList(0, i);
                        result.addAll(preList);
                        return result;
                    }
                }
            }
        }
        return imgs;
    }
}
